package org.gikolet.ch2.android.io;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;

import org.apache.commons.io.input.CountingInputStream;
import org.gikolet.ch2.data.Res;
import org.gikolet.ch2.io.Parser;
import org.gikolet.ch2.io.ResesReader;
import org.gikolet.util.Tuple.Tuple2;

public class Ch2DatInputStreamParser implements ResesReader {

	private Parser<Tuple2<Res, String>> parser = new Ch2ResPAF();

	private BufferedReader reader;

	private boolean firstRecord;
	private String subject;

	private CountingInputStream countIn;

	private int readResCount = 0;

	public Ch2DatInputStreamParser(InputStream in, String charsetName)
			throws IOException {
		this(in, Charset.forName(charsetName));
	}

	public Ch2DatInputStreamParser(InputStream in, Charset charset)
			throws IOException {

		this.firstRecord = true;

		this.countIn = new CountingInputStream(in);
		this.reader = new BufferedReader(new InputStreamReader(this.countIn,
				charset));
	}

	public String getSubject() {
		return this.subject;
	}

	public Res read() throws IOException {
		String line = this.reader.readLine();

		if (line == null) {
			return null;
		}

		Tuple2<Res, String> res = parser.parse(line);

		if (this.firstRecord) {
			this.subject = res._2;

			this.firstRecord = false;
		}

		this.readResCount++;
		return res._1;
	}

	public void close() throws IOException {
		this.reader.close();
	}

	public long getContentLength() {
		return -1;
	}

	public long getReadContentLength() {
		return this.countIn.getByteCount();
	}

	public int getReadResCount() {
		return this.readResCount;
	}
}
